﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Portal.FileSystemData;
using System.IO;

namespace Portal.Modules.ImageBrowser
{
  public partial class StateEditTexts : Portal.StateBase.ModuleState
  {
    DataAccessor _dataAccessor;
    CacheAgent _cacheAgent;

    protected void Page_Load(object sender, EventArgs e)
    {
      _dataAccessor = new DataAccessor(Document);
      _cacheAgent = new CacheAgent(_dataAccessor);

      if (_dataAccessor.Config.ThumbnailCount > 0)
        _dataPager.PageSize = _dataAccessor.Config.ThumbnailCount;
      else
        _dataPager.PageSize = int.MaxValue;

      // Show the Breadcrumb only, if there are directories involved.
      if (_dataAccessor.RootDirectory.SubDirCount > 0)
      {
        _breadCrumbDiv.Visible = true;
        CreateBreadCrumbs(_breadcrumb);
      }
      else
        _breadCrumbDiv.Visible = false;

      if (TransitionArgument != null)
      {
        FileWrapper fileWrap = _dataAccessor.RootDirectory.GetFile(TransitionArgument as string);
        if (fileWrap != null)
        {
          int index = fileWrap.Parent.GetFileIndex(fileWrap.Name);
          if (index >= 0)
          {
            int maxCount = _dataAccessor.Config.ThumbnailCount;
            index = ((int)((index) / maxCount)) * maxCount;
            if (index > 0)
              _dataPager.SetPageProperties(index, maxCount, false);
          }
          CurrentPath = fileWrap.Parent.VirtualPath;
        }
      }

      if (!ControlPostback)
      {
        SetBoundData();

      }
    }

    private void SetBoundData()
    {
      _captionEdit.Text = CurrentDirectory.PresentationName;
      _tooltipEdit.Text = CurrentDirectory.Tooltip;
      _descriptionEdit.Text = CurrentDirectory.Description;
      _sortOrderAsc.Checked = CurrentDirectory.SortOrderAsc;
    }

    protected void OnBack(object sender, EventArgs e)
    {
      ProcessEvent((int)EditStateEvent.Back);
    }


    protected void OnDirectoryContentSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
      e.InputParameters["dataAccessor"] = _dataAccessor;
      e.InputParameters["relativePath"] = CurrentPath;
    }

    protected string GetImageUrl(object item)
    {
      return _cacheAgent.GetThumbnailImageUrl(item as FileSystemWrapper);
    }

    protected string GetThumbImgStyle()
    {
      int maxSize = _dataAccessor.Config.ThumbCfg.MaxSize;
      if (_dataAccessor.Config.ThumbCfg.HasShadow)
        maxSize += _dataAccessor.Config.ThumbCfg.ShadowWidth * 2;
      return "height: " + maxSize.ToString() + "px;width: " + maxSize.ToString() + "px;" + "float:left";
    }

    /// <summary>
    /// The current selected directory.
    /// </summary>
    protected string CurrentPath
    {
      get
      {
        return ViewState["CurrentPath"] as string;
      }
      set
      {
        if (((string)ViewState["CurrentPath"]) != value)
        {
          ViewState["CurrentPath"] = value;
          _currentDir = null;
          _pictureList.DataBind();
          _breadcrumb.Controls.Clear();
          CreateBreadCrumbs(_breadcrumb);
        }
      }
    }

    private DirectoryWrapper _currentDir = null;

    /// <summary>
    /// The current selected Directory Wrapper.
    /// </summary>
    protected DirectoryWrapper CurrentDirectory
    {
      get
      {
        if (_currentDir == null)
        {
          if (string.IsNullOrEmpty(CurrentPath))
            _currentDir = _dataAccessor.RootDirectory;
          else
            _currentDir = _dataAccessor.RootDirectory.GetSubDirectory(CurrentPath);
        }
        return _currentDir;
      }
    }

    private void CreateBreadCrumbs(Control targetCtrl)
    {
      DirectoryWrapper directory = CurrentDirectory;
      
      if (null != directory)
      {
        // Add current directory.
        Literal currLayer = new Literal();
        currLayer.Text = directory.PresentationName;
        targetCtrl.Controls.Add(currLayer);

        // Add all parent directories.
        DirectoryWrapper dir = directory.Parent;
        int step = 0;
        while (dir != null)
        {
          targetCtrl.Controls.AddAt(0, new LiteralControl(" >> "));

          var dirLayer = new LinkButton();
          dirLayer.ID = "DirUp" + step++; // Necessary for a working Eventhandling.
          dirLayer.Text = dir.PresentationName;
          dirLayer.CommandArgument = dir.VirtualPath;
          dirLayer.Command += new CommandEventHandler(OnChangeDir);
          targetCtrl.Controls.AddAt(0, dirLayer);

          dir = dir.Parent;
        }

        if (CurrentDirectory.SubDirCount > 0)
        {
          _subDirectory.Visible = true;

          _subDirectory.DataSource = CurrentDirectory.SubDirectories;
          _subDirectory.DataTextField = "PresentationName";
          _subDirectory.DataValueField = "VirtualPath";
          _subDirectory.DataBind();
          _subDirectory.Items.Insert(0, "");
          _subDirectory.SelectedIndex = 0;
        }
        else
          _subDirectory.Visible = false;
      }
      else
      {
        string dirNotFound = Portal.Api.Language.GetText(Portal.Api.Module.GetModuleControl(this), "DirectoryNotFound");
        targetCtrl.Controls.AddAt(0, new LiteralControl("<i>" + dirNotFound + "</i>"));
      }
    }

    void OnChangeDir(object sender, CommandEventArgs e)
    {
      Save();
      CurrentPath = e.CommandArgument as string;
    }


    protected void OnSave(object sender, EventArgs e)
    {
      if(Save())
        ProcessEvent((int)EditStateEvent.Back);

    }

    /// <summary>
    /// Saves the configuration.
    /// </summary>
    private bool Save()
    {
      bool success = false;

	    DirectoryWrapper directory = CurrentDirectory;
      if(directory != null)
      {
        directory.BeginBulkUpdate();
        foreach(var Row in _pictureList.Items)
        {
          string fileName = (string) _pictureList.DataKeys[Row.DataItemIndex]["Name"];
          FileWrapper fileWrp = directory.GetFile(fileName);
          if (fileWrp != null)
          {
            TextBox TextBox = (TextBox)Row.FindControl("_captionEdit");
            fileWrp.PresentationName = TextBox.Text;

            TextBox = (TextBox)Row.FindControl("_tooltipEdit");
            fileWrp.Tooltip = TextBox.Text;

            TextBox = (TextBox)Row.FindControl("_descriptionEdit");
            fileWrp.Description = TextBox.Text;
          }
        }

        directory.PresentationName = _captionEdit.Text;
        directory.Tooltip = _tooltipEdit.Text;
        directory.Description = _descriptionEdit.Text;
        directory.SortOrderAsc = _sortOrderAsc.Checked;

        directory.EndBulkUpdate();

        success = true;
      }
      return success;
    }

    protected void OnFolderSelected(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(_subDirectory.SelectedValue))
      {
        Save();
        CurrentPath = _subDirectory.SelectedValue;
        SetBoundData();
      }
    }
  }
}